// pages/canteen/login/login.js
Page({

  /**
   * 页面的初始数据
   */
  data: {

  },


  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    
  },

  onClickLeft() {
    wx.navigateBack()
  },

  onChange(event) {
    console.log(event)
    var that = this;
    if(event.currentTarget.id=="password") {
      if(event.detail.length < 6) {
        that.setData({
          pwdMsg: "密码长度小于6位"
        })
      }else {
        that.setData({
          pwdMsg: ""
        })
      }
    }else{
      if(event.detail.length == 0) {
        that.setData({
          accMsg: "账号不能为空"
        })
      }else {
        that.setData({
          accMsg: ""
        })
      }
    }
  },

  formSubmit (e) {
    var that = this;
    console.log('表单提交数据', e.detail.value)
    var userAccount = e.detail.value.userAccount;
    var password = e.detail.value.password;
    if(userAccount.length == 0) {
      that.setData({
        accMsg: "账号不能为空"
      })
    }
    if(password.length < 6) {
      that.setData({
        pwdMsg: "密码长度小于6位"
      })
    }

    console.log('进行用户登录的判断')

    if(userAccount.length != 0 && password.length >= 6) {
      wx.cloud.callFunction({
        name: 'lu',
        data: {
          action: 'rootlogin',
        },
        success(res) {
          console.log(res)
          let users = res.result.data
          let flag = false
          for(let user of users) {
            if(user.window_root===userAccount && user.window_pwd===password) {
              flag = true
              wx.setStorageSync('canteen', user.canteen)
              wx.setStorageSync('window_name', user.window_name)
              wx.setStorageSync('window_id', user._id)
              break
            }
          }
          if(flag) {
            wx.setStorageSync('login', true)
            wx.navigateTo({
              url: '../manager?status=0',
            })
          } else {
            wx.setStorageSync('login', false)
            that.setData({
              pwdMsg: "密码错误"
            })
          }
          console.log("云函数获取数据成功",res)
        },
        fail(res) {
          console.log("函数获取数据失败",res)
        }
      })
    }
  },
})